package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.feign.AdminFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticlesService;
import com.heima.common.constants.article.ArticleConstans;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @作者 itcast
 * @创建日期 2021/2/24 11:05
 **/
@Service
@Slf4j
@Transactional
public class HotArticlesServiceImpl implements HotArticlesService {
    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public void computeHotArticle() {
        // 1. 按照当前时间，获取前5天的时间节点
        String dayParams = DateTime.now().minusDays(5).toString("yyyy-MM-dd hh:mm:ss");
        // 2. 查询近5天的所有article文章
        List<ApArticle> apArticles = apArticleMapper.loadArticleForhot(dayParams);
        // 3. 计算每一篇文章的分值
        List<HotArticleVo> hotArticleVoList = computeHotArticle(apArticles);
        // 4. 按频道缓存热点文章列表
        cacheToRedisByTag(hotArticleVoList);
    }
    @Autowired
    AdminFeign adminFeign;
    /**
     *
     * @param hotArticleVoList  所有频道 近5天的 全部文章
     */
    private void cacheToRedisByTag(List<HotArticleVo> hotArticleVoList) {
        if(hotArticleVoList == null){
            return;
        }
        // 1. 远程查询频道列表
        ResponseResult responseResult = adminFeign.selectAllChannel();
        // responseResult的getData是object 强转频道列表会报错，所以又使用JSON重新封装了下
        List<AdChannel> channelList = JSONArray.parseArray(JSON.toJSONString(responseResult.getData()), AdChannel.class);
        // 2. 按照频道   每个频道缓存热度值最高的30条文章数据
        for (AdChannel adChannel : channelList) {
            // 找到属于当前频道的文章列表
            List<HotArticleVo> articlesByChannel = hotArticleVoList.stream().filter(articleVo -> articleVo.getChannelId() == adChannel.getId()).collect(Collectors.toList());
            // 缓存  key: hot_article_first_page_ 频道id
            sortAndRedis(articlesByChannel,ArticleConstans.HOT_ARTICLE_FIRST_PAGE+adChannel.getId());
        }
        // 3. 推荐频道   取全部数据的热度值最高的前30条文章数据
        // 缓存 key: hot_article_first_page___all__
        sortAndRedis(hotArticleVoList,ArticleConstans.HOT_ARTICLE_FIRST_PAGE+ArticleConstans.DEFAULT_TAG);
    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private void sortAndRedis(List<HotArticleVo> hotArticleVoList , String redisKey){
        // 按照热度得分降序排序   取前30条数据
        List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        // 缓存到redis中
        stringRedisTemplate.opsForValue().set(redisKey,JSON.toJSONString(hotArticleVos));
    }
    /**
     * 计算所有文章分值
     * @param apArticles
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticles) {
        //1. 检查文章集合是否为空
        if(apArticles == null || apArticles.isEmpty()){
            log.error("查询近5天文章列表为空");
            return null;
        }
        //2. 遍历所有文章
        //3. 返回vo 集合                流对象 -->  方法(流对象)
        return apArticles.stream().map(this::computeScore).collect(Collectors.toList());
    }

    /**
     * 计算每一篇文章的热度值
     * @param apArticle
     * @return
     */
    private HotArticleVo computeScore(ApArticle apArticle) {
        // 2.1 封装vo对象
        HotArticleVo articleVo = new HotArticleVo();
        BeanUtils.copyProperties(apArticle,articleVo);
        // 2.2 计算每篇文章分值
        Integer score = 0;
        if(apArticle.getViews()!=null){ // 30
            score += apArticle.getViews();
        }
        if(apArticle.getLikes()!=null){ // 30
            score += apArticle.getLikes() * ArticleConstans.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getComment()!=null){ // 30
            score += apArticle.getComment() * ArticleConstans.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection()!=null){ // 30
            score += apArticle.getCollection() * ArticleConstans.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        articleVo.setScore(score);
        return articleVo;
    }
}
